import { memo, useMemo } from 'react'
import { useDrop } from 'react-dnd'
import type { FC } from 'react'
import { Command } from '../Command'
import { ItemTypes } from './ItemTypes'
import { useAppStore } from '@renderer/pages/designer/store/appStore'
import { deriveCommandLevels } from '@repo/executor/src/playback_tree/command_leveler';

// 测试用例的节点列表
const CommandList: FC = memo(function Container({ commands, taskId }: any) {

  const moveViewCommand = useAppStore((state) => state.actions.moveViewCommand);
  const executionResult = useAppStore((state) => state.executionResult);

  // 当前任务执行结果
  const taskExecutionResult: {
    dones: Set<number>, // 成功的
    errors: Set<number>, // 失败的
    warnings: Set<number> // 报警的
  } = useMemo(() => {
    return executionResult.get(taskId) || {
      dones: new Set(),
      errors: new Set(), // 失败的
      warnings: new Set() // 报警的
    }
  }, [executionResult, taskId]);

  const levels = deriveCommandLevels(commands);
  const [, drop] = useDrop(() => ({
    accept: [ItemTypes.CARD, ItemTypes.CMD],
    hover(item: any, monitor) {
      const isOver = monitor.isOver({ shallow: true })
      if (isOver && commands.length === 0) {
        const dragIndex = item.dragIndex;
        const hoverIndex = 0;
        if (dragIndex === hoverIndex) {
          return
        }
        moveViewCommand(dragIndex, hoverIndex, {
          cmd: item.cmd,
          description: item.description
        })
        item.dragIndex = hoverIndex;
      }
    },
  }), [commands])

  return (
    <div ref={drop} className='h-full p-4 overflow-auto '>
      {commands.map((command: any, index: number) => (
        <Command
          key={index}
          index={index}
          moveCommand={moveViewCommand}
          commandData={command}
          level={levels[index]}
          taskExecutionResult={taskExecutionResult}
        />
      ))}
    </div>
  )
})

export default CommandList
